const fs = require('fs');
const router = require('koa-router')();

// 映射到具体方法上
function mapping(url, api, moduleName) {
    const path = `/api/${moduleName.split('.js')[0]}${url.split(' ')[1]}`;
    const method = url.split(' ')[0]; 
    switch (method) {
        case 'GET':
            router.get(path, api);
            break;
        case 'POST':
            router.post(path, api);
            break;
        case 'PUT':
            router.put(path, api);
            break;
        case 'DELETE':
            router.del(path, api);
            break;
        default:
            console.log(`模块 ${module} 方法错误`);
            break;
    }
}

// 进入拦截器
async function interceptor(ctx, next) {
    // 设置Content-Type:
    ctx.response.type = 'application/json';
    ctx.return = (msg, data) => {
        ctx.response.body = {
            msg,
            data
        };
    }

    await next();
}

module.exports = (app) => {
    // 遍历模块并添加路由
    fs.readdirSync(`${__dirname}/../controllers`).forEach((moduleName) => {
        const apis = require(`${__dirname}/../controllers/${moduleName}`);
        for (const key in apis) {
            mapping(key, apis[key], moduleName);
        }
    });
    
    // 拦截器
    app.use(interceptor);

    // 注册路由
    app.use(router.routes());
}